package cn.lena.leecode.arr;

import org.junit.Test;

/**
 * @author lena
 * @date 2021/6/22
 */
public class Offer29 {

	/**
	 * 顺时针打印矩阵
	 * @param matrix 输入矩阵
	 * @return
	 */
	public int[] spiralOrder(int[][] matrix) {
		if(matrix.length == 0) {
			return new int[0];
		}
		int x=matrix.length;int y=matrix[0].length;
		// 用一个boolean数组存储是否打印过
		boolean[][] visited=new boolean[x][y];
		int i=0,j=0,k=0;
		int[] result=new int[x*y];
		// 右->下->左->上
		while(true) {
			// 向右
			while(k<result.length && j<y) {
				System.out.println("right"+"("+i+","+j+")");
				if(!visited[i][j]){
					//System.out.println("right:"+matrix[i][j]);
					result[k++]=matrix[i][j];
					visited[i][j++]=true;
				}else{
					break;
				}
			}
			j--;i++;
			// 向下
			while(k<result.length && i<x) {
				System.out.println("down"+"("+i+","+j+")");
				if(!visited[i][j]){
					//System.out.println("down:"+matrix[i][j]);
					result[k++]=matrix[i][j];
					visited[i++][j]=true;
				}else{
					break;
				}
			}
			i--;j--;
			// 向左
			while(k<result.length && j<y && i<x && i>=0 && j>=0) {
				System.out.println("left"+"("+i+","+j+")");
				if(!visited[i][j]){
					//System.out.println("left:"+matrix[i][j]);
					result[k++]=matrix[i][j];
					visited[i][j--]=true;
				}else{
					break;
				}
			}
			j++;i--;
			// 向上
			while(k<result.length && j<y && i<x && i>=0 && j>=0) {
				System.out.println("up"+"("+i+","+j+")");
				if(!visited[i][j]){
					//System.out.println("up:"+matrix[i][j]);
					result[k++]=matrix[i][j];
					visited[i--][j]=true;
				}else{
					break;
				}
			}
			if(k == result.length) {
				break;
			}
			i++;j++;
		}
		return result;
	}


	@Test
	public void test(){
		int[][] matrix={};
		int[] result = spiralOrder(matrix);
		for(int a:result){
			System.out.printf(a+",");
		}
	}

}
